<?php

namespace app\admin\controller;

use app\common\service\BalanceService;
use think\Db;

class Reward extends Common {

	
	public function jlj(){
		return $this->fetch();
	}
	public function jlj2(){
		return $this->fetch();
	}

	public function ex(){
		return $this->fetch();
	}
	public function ex2(){
		$data = Db::table('tp_invest_config')->where('id','>',0)->select();
		$this->assign('data',$data);
		return $this->fetch();
	}
	public function yhj(){
		return $this->fetch();
	}
	public function yhj2(){
		return $this->fetch();
	}
	public function hb(){
		return $this->fetch();
	}
	public function hb2(){
		return $this->fetch();
	}
	public function hbList(){
		$limit = request()->param('limit') ?: 20;
		$username = request()->param('username');
		$uid = request()->param('uid');
		$uuid = request()->param('uuid');
		$type = request()->param('type');
		$wid = request()->param('wid');
		$code = request()->param('code');
		$hb_code = request()->param('hb_code');
		$status = request()->param('status');
		$is_active = request()->param('is_active');
		$where      = '1=1';
		if ($username != '') {
            $where .= ' and u.username like \'%' . $username . '%\'';
        }
        if ($code != '') {
            $where .= ' and a.code like \'%' . $code . '%\'';
        }
        if ($hb_code != '') {
            $where .= ' and a.hb_code like \'%' . $hb_code . '%\'';
        }
        if($status != '') {
            $where .= ' and a.status='.$status;
        }
        // if($type != '') {
        //     $where .= ' and a.type='.$type;
        // }
 		if ($this->admin_info['level'] != 1) {
 			// $where .= ' and a.admin_uid='.$this->admin_info['id'];
 		}
 		if($uuid != '') {
			if (!in_array($uuid, $this->data_uids_arr)) {
				return $this->tableData([]);
				// return ['code' => 1, 'msg' => '权限不足'];
			} else {

				$data_uids_arr = Db::table('tp_user_team')->where('uid',$uuid)->column('x_uid');
				$data_uids_arr[] = $uuid;
				$daaaa = implode($data_uids_arr, ',');
				$where .= ' and a.uid in ('.$daaaa.')';
			}
		}

		if($uid != '') {
			if (!in_array($uid, $this->data_uids_arr)) {
				// return ['code' => 1, 'msg' => '权限不足'];
				return $this->tableData([]);
			} else {
				$where .= ' and a.uid='.$uid;
			}
		}else {
			if ($this->data_uids_string) {
				$where .= ' and a.uid in ('.$this->data_uids_string.')';
			}
		}

 	// 	if($uid != '') {
		// 	if (!in_array($uid, $this->data_uids_arr)) {
		// 		return $this->tableData([]);
		// 	}
		// 	$where .= ' and a.uid='.$uid;
		// } 
		$data = Db::table('tp_invest_code2')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->join('tp_admin m', 'm.id = a.admin_uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,m.name adminname,u.username')
				->paginate($limit);
		$data = $data->toArray();
		if(empty($data['data'])){
			$data['data']  = Db::table('tp_invest_code2')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->join('tp_admin m', 'm.id = a.admin_uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,m.name adminname,u.username')
				->page(1)
				->limit($limit)
				->select();		
		}
		return $this->tableData($data);
	}
	public function rewardList(){
		$limit = request()->param('limit') ?: 20;
		$username = request()->param('username');
		$uid = request()->param('uid');
		$type = request()->param('type');
		$wid = request()->param('wid');
		$status = request()->param('status');
		$is_active = request()->param('is_active');
		$where      = '1=1';
		if ($username != '') {
            $where .= ' and u.username like \'%' . $username . '%\'';
        }
        if($status != '') {
            $where .= ' and a.status='.$status;
        }
        if($type != '') {
            $where .= ' and a.type='.$type;
        }
 		if ($this->admin_info['level'] != 1 && $this->admin_info['level'] != 2) {
 			$where .= ' and a.admin_uid='.$this->admin_info['id'];
 		}
 		if($uid != '') {
			if (!in_array($uid, $this->data_uids_arr)) {
				return $this->tableData([]);
			}
			$where .= ' and a.uid='.$uid;
		} else {
			if ($this->data_uids_string) {
				$where .= ' and a.uid in ('.$this->data_uids_string.')';
			}
		}
// 		var_dump($where);die();
		$data = Db::table('tp_invest_code')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->join('tp_admin m', 'm.id = a.admin_uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,m.name adminname,u.username')
				->paginate($limit);
		$data = $data->toArray();
		if(empty($data['data'])){
			$data['data']  = Db::table('tp_invest_code')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->join('tp_admin m', 'm.id = a.admin_uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,m.name adminname,u.username')
				->page(1)
				->limit($limit)
				->select();		
		}
		return $this->tableData($data);
	}
	public function sq(){
		if (request()->method() == 'POST') {
			$data = [];
			$uid = request()->param('uid')?:0;
			$type = request()->param('type')?:'';
			$remark = request()->param('remark')?:'';
			$amount = request()->param('amount')?:'';
			$robot = request()->param('robot')?:0;
			$num = request()->param('num')?:1;
			Db::startTrans();
			if ($robot) {
				$remark = Db::table('tp_invest_config')->where('id',$robot)->value('name');
			}
			if($uid != 0) {
				if (!in_array($uid, $this->data_uids_arr)) {
					return ['code' => 1, 'msg' => '权限不足'];
				}
			}
			for ($i=0; $i < $num; $i++) { 
				$code = $this->setCode();

				$res = Db::table('tp_invest_code')->insert([
					'uid'=>$uid,
		            'code'=>$code,
		            'amount'=>$amount,
		            'status'=>1,
		            'type'=>$type,
		            'create_date'=>date('Y-m-d H:i:s'),
		            'remark'=>$remark,
		            'order_id'=>0,
		            'robot'=>$robot,
		            'admin_uid'=>$this->uid
		        ]);
		        if (!$res) {
		        	Db::rollback();
		        	return ['code' => 1, 'msg' => '申请失败'];
		        }
			}
			Db::commit();
		    return ['code' => 0, 'msg' => '申请成功，等待审核'];			
		} else {
			$id   = request()->param('id');
			return $this->fetch();
		}
	}
	public function delhb(){
		$id = request()->param('id');
		$res = Db::table('tp_invest_code2')->where('id',$id)->delete();
		if ($res) {
			return ['code'=>0,'msg'=>'success'];
		} else {
			return ['code'=>1,'msg'=>'fail'];
		}
	}
	public function sqHb(){
		if (request()->method() == 'POST') {
			$data = [];
			$uid = request()->param('uid')?:0;
			$type = request()->param('type')?:'';
			$remark = request()->param('remark')?:'';
			$amount = request()->param('amount')?:'';
			$robot = request()->param('robot')?:0;
			$num = request()->param('num')?:1;
			Db::startTrans();
			if (!in_array($this->admin_info['level'], [1,2])) {
				return ['code' => 1, 'msg' => '权限不足'];
			}
			$left_amount = $amount;
			$code = $this->setCode2();
			$arr2 = ['0','0.05'];
			for ($i=1; $i < $num+1; $i++) { 
				$addd = $arr2[array_rand($arr2)];
				$hb_code = $this->setCode3();
				if ($num == 1) {
					$sigle_amount = $amount;
				} else if ($i == 1) {
					$sigle_amount = round(mt_rand(15,20) * $left_amount/100,1) + $addd;
					$left_amount = $left_amount - $sigle_amount;
				} else if ($i == $num) {
					$sigle_amount = $left_amount;
					if ($sigle_amount <0.01) {
						$sigle_amount = 0.01;
					}
				} else if($i != 1 && $i != $num){
					if ($num > 10) {
						if ($i == 2 || $i == 3) {
							$sigle_amount = 0.05;
						} else{
							$sigle_amount = round($left_amount/($num-$i+1) * mt_rand(75,125) / 100,1) + $addd;
							if ($sigle_amount <0.01) {
								$sigle_amount = 0.01;
							}
						}
					} else {
						$sigle_amount = round($left_amount/($num-$i+1) * mt_rand(75,125) / 100,1) + $addd;
						if ($sigle_amount <0.01) {
							$sigle_amount = 0.01;
						}
					}
					
					$left_amount = $left_amount - $sigle_amount;
				}
				$res = Db::table('tp_invest_code2')->insert([
					'uid'=>$uid,
		            'code'=>$code,
		            'hb_code'=>$hb_code,
		            'num'=>$num,
		            'total_amount'=>$amount,
		            'amount'=>$sigle_amount,
		            'status'=>1,
		            'type'=>$type,
		            'create_date'=>date('Y-m-d H:i:s'),
		            'admin_uid'=>$this->uid
		        ]);
		        if (!$res) {
		        	Db::rollback();
		        	return ['code' => 1, 'msg' => '申请失败'];
		        }
			}
			Db::commit();
		    return ['code' => 0, 'msg' => '申请成功，等待审核'];			
		} else {
			$id   = request()->param('id');
			return $this->fetch();
		}
	}
	public function setCode(){
        $str = md5(uniqid().microtime().rand(10000,90000));
        $code = substr($str, 0,8);
        $res = Db::table('tp_invest_code')->where('code',$code)->find();
        if($res){
            $this->setCode();
        } else {
            return $code;
        }
    }
public function setCode2(){
        $str = md5(uniqid().microtime().rand(10000,90000));
        $code = substr($str, 0,8);
        $res = Db::table('tp_invest_code2')->where('code',$code)->find();
        if($res){
            $this->setCode();
        } else {
            return $code;
        }
    }
    public function setCode3(){
        $str = md5(uniqid().microtime().rand(10000,90000));
        $code = substr($str, 0,6);
        $res = Db::table('tp_invest_code2')->where('hb_code',$code)->find();
        if($res){
            $this->setCode();
        } else {
            return $code;
        }
    }

    public function ffhb(){
    	if (request()->method() == 'POST') {
			$data = [];
			$id = intval(request()->param('id'));
			// $remark = request()->param('value');
			
			Db::startTrans();
			$info = Db::table('tp_invest_code2')->where('id', $id)->lock(true)->find();
			if (empty($info)) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单不存在'];
			}
			

			if ($info['status'] != 2 || empty($info['uid'])) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单状态有误'];
			}
			if($info['uid']) {
				if (!in_array($info['uid'], $this->data_uids_arr)) {
					Db::rollback();
					return ['code' => 1, 'msg' => '权限不足'];
				}
			}
			$res1 = Db::table('tp_invest_code2')->where('id', $id)->update([
				'status'=>3
			]);
			$res2 = BalanceService::updateBalance($info['uid'],1,$info['amount'],'红包转入',15);
			if ($res1 && $res2) {
				Db::commit();
				return ['code' => 0, 'msg' => '审核通过，红包已到账'];
			} else {
				Db::rollback();
				return ['code' => 1, 'msg' => '审核失败'];
			}	
		}
    }
    public function ffhb2(){
    	// var_dump(1);die();
    	if (request()->method() == 'POST') {
			if (!in_array($this->admin_info['level'], [1])) {
				return ['code' => 1, 'msg' => '权限不足'];
			}

			$data = request()->param('data');

			$remark = request()->param('value');
			$data = explode(',', $data);
			// $data = json_decode($data,1);
			// var_dump(json_last_error());
			// var_dump($data);die();
			$data = Db::table('tp_invest_code2')->where('id','in',$data)->select();
			if ($data) {
				Db::startTrans();
				// var_dump(2);
				$ids = array_column($data, 'id');
				$has = Db::table('tp_invest_code2')->where('id','in',$ids)->where('status','<>',2)->find();
				if ($has) {

					return ['code' => 1, 'msg' => '存在未领取或已发放的红包'];
				}

				$date = date('Y-m-d H:i:s');
				foreach ($data as $key => $val) {
					$info = $val;
					if (empty($info)) {
						Db::rollback();
						return ['code' => 1, 'msg' => '订单不存在'];
					}
					

					if ($info['status'] != 2 || empty($info['uid'])) {
						Db::rollback();
						return ['code' => 1, 'msg' => '订单状态有误'];
					}
					if($info['uid']) {
						if (!in_array($info['uid'], $this->data_uids_arr)) {
							Db::rollback();
							return ['code' => 1, 'msg' => '权限不足'];
						}
					}
					$res1 = Db::table('tp_invest_code2')->where('id', $id)->update([
						'status'=>3
					]);
					$res2 = BalanceService::updateBalance($info['uid'],1,$info['amount'],'红包转入',15);
					if ($res1 && $res2) {
						// Db::commit();
						// return ['code' => 0, 'msg' => '审核通过，红包已到账'];
					} else {
						Db::rollback();
						return ['code' => 1, 'msg' => '审核失败'];
					}
				}
				$res = Db::table('tp_invest_code2')->where('id','in',$ids)->update([
					'status'=>3,
				]);
					
				if ($res) {
					Db::commit();
					return ['code' => 0, 'msg' => '审核通过，红包已到账'];
				} else {
					Db::rollback();
					return ['code' => 1, 'msg' => '操作失败'];
				}
			} else {
				return ['code' => 1, 'msg' => '系统错误'];
			}
		}
    }
	public function pass() {
		if (request()->method() == 'POST') {
			if (!in_array($this->admin_info['level'], [1,2])) {
				return ['code' => 1, 'msg' => '权限不足'];
			}

			$data = [];
			$id = intval(request()->param('id'));
			//$remark = request()->param('value');
			
			Db::startTrans();
			$info = Db::table('tp_invest_code')->where('id', $id)->lock(true)->find();
			if (empty($info)) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单不存在'];
			}
			

			if ($info['status'] != 1) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单状态有误'];
			}
			if ($this->admin_info['level'] == 2) {
				// if ($info['uid'] == $this->admin_info['data_uid']) {
				// 	return ['code' => 1, 'msg' => '权限不足'];
				// }
				if (!in_array($info['uid'], $this->data_uids_arr)) {
					return ['code' => 1, 'msg' => '权限不足'];
				}
			}
			if ($info['type'] == 3) {
				$res1 = Db::table('tp_invest_code')->where('id', $id)->update([
					'status'=>3
				]);
				$res2 = BalanceService::updateBalance($info['uid'],1,$info['amount'],'奖励金转入',15);
				if ($res1 && $res2) {
					Db::commit();
					return ['code' => 0, 'msg' => '审核通过，奖励金已到账'];
				} else {
					Db::rollback();
					return ['code' => 1, 'msg' => '审核失败'];
				}
			} else {
				$res = Db::table('tp_invest_code')->where('id', $id)->update([
					'status'=>2
				]);
				if (!$res) {
					Db::rollback();
					return ['code' => 1, 'msg' => '审核失败'];
				} else {
					Db::commit();
					return ['code' => 0, 'msg' => '审核成功'];
				}
			}
					
		}
	}

	public function refuse() {
		if (request()->method() == 'POST') {
			if (!in_array($this->admin_info['level'], [1,2])) {
				return ['code' => 1, 'msg' => '权限不足'];
			}
			$data = [];
			$id = intval(request()->param('id'));
			// $remark = request()->param('value');
			
			Db::startTrans();
			$info = Db::table('tp_invest_code')->where('id', $id)->lock(true)->find();
			if (empty($info)) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单不存在'];
			}
			

			if ($info['status'] != 1) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单状态有误'];
			}
			$res = Db::table('tp_invest_code')->where('id', $id)->update([
				'status'=>4
			]);
			if (!$res) {
				Db::rollback();
				return ['code' => 1, 'msg' => '审核失败'];
			} else {
				Db::commit();
				return ['code' => 0, 'msg' => '审核成功'];
			}		
		}
	}
}
